package cn.thornbird.orgsync.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CookieUtil {

    public static final int DEFAULT_COOKIE_MAX_AGE = 60 * 60 * 24;

    public static String getCookieValue(HttpServletRequest request, String name) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        int count = cookies == null ? 0 : cookies.length;
        for (int i = 0; i < count; i++) {
            if (cookies[i].getName().equals(name)) {
                value = cookies[i].getValue();
                break;
            }
        }
        return value;
    }

    public static void setCookieValue(HttpServletResponse response, String name, String value) {
        setCookieValue(response, name, value, DEFAULT_COOKIE_MAX_AGE);
    }

    public static void setCookieValue(HttpServletResponse response, String name, String value, int expiry) {
        if (value == null) {
            value = "";
            expiry = 0;
        }
        try {
            value = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("error", e);
        }
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
    }

}
